const express = require('express')
const { red } = require('chalk')
const router = express.Router()
const { insertAddressList, getAddressList, modifyAddressList, removeAddressList } = require('../../model/mongo')

router.get('/list', async (req, res) => {
    let { userid } = req.query
    let result = {
        code: 200,
        msg: '获取地址列表'
    }
    result.data = await getAddressList(userid)
    res.send(JSON.stringify(result))
})

router.post('/add', async (req, res) => {
    let result = {
        code: 200,
        msg: '添加地址'
    }
    let {
        userid,
        name,
        tel,
        province,
        city,
        county,
        addressDetail,
        isDefault
    } = req.body

    if (isDefault === 1 || isDefault === '1' || isDefault === 'true') {
        isDefault = true
    }
    if (isDefault === 0 || isDefault === '0' || isDefault === 'false') {
        isDefault = false
    }
    result.data = await insertAddressList({ userid, name, tel, province, city, county, addressDetail, isDefault })
    res.send(JSON.stringify(result))
})

router.post('/update', async (req, res) => {
    let result = {
        code: 200
    }
    result.msg = await modifyAddressList(req.body)
    res.send(JSON.stringify(result))
})

router.post('/delete', async (req, res) => {
    let result = {
        code: 200
    }
    let { addressid } = req.body
    result.msg = await removeAddressList(addressid)
    res.send(JSON.stringify(result))
})

module.exports = router
